package itpenguin;

import itpenguin.common.Util;
import itpenguin.entities.Article;
import itpenguin.entities.ImageSrc;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Article control
 *
 */
public class TobogganServlet extends CrecheServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String[] key = Util.GetKey(req);
		
		if (key == null)
		{
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
		Article article = Util.GetArticle(key[0], true);
		if (article == null) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return ;
		}
		 
		int section = 1;
		if (key.length > 1)
		{
			try
			{
				section = Integer.parseInt(key[1]);
			}
			catch (NumberFormatException e) {
				resp.sendError(HttpServletResponse.SC_NOT_FOUND);
				return;
			}
		}
		if (section < 1 || section > article.getSections().size())
		{
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
	    Pattern srcPt = Pattern.compile("(<img\\s.*src=\")(.+?)(\".*?/>)");
		Matcher srcMt = srcPt.matcher(article.getSections().get(section - 1));
	    StringBuffer sb = new StringBuffer();
	    while (srcMt.find()) {
	    	for(ImageSrc is : article.getImageMap()) {
	    		if (is.getOriginalSrc().equals(srcMt.group(2))) {
    				srcMt.appendReplacement(sb, "$1" 
    						+ is.getRemoteSrc()
    							.replaceFirst("/s\\d{3,4}/", "/s800/")
    							.replaceFirst("https://", "http://") + "$3");
	    	    	break;
	    		}
	    	}
	    }
	    srcMt.appendTail(sb);

		req.setAttribute("currentSection", sb.toString());
		req.setAttribute("section", section);
		
		req.setAttribute("seriesList", 
				Util.GetSeriesList(article.getParentId()));
		
		req.setAttribute("parent", Util.GetSeries(article.getParentId()));
		
		forwardToJsp(req, resp, article);
	}

}
